package net.wwang.blog.util;

import net.wwang.blog.commons.global.Constants;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author WangWei
 * @date 2020/8/14
 */
public class CookieUtil {
    public static  final String domain = "127.0.0.1";
    public static void setCookie(HttpServletResponse response, String key, String value){
        setCookie(response,key,value, Constants.TimeValue.TIME_COOKIE_ONE_YEAR);
    }
    public static void setCookie(HttpServletResponse response, String key, String value, int age){
        Cookie cookie = new Cookie(key, value);
        cookie.setPath("/");
        cookie.setDomain(domain);
        cookie.setMaxAge(age);
        response.addCookie(cookie);
    }

    /**
     * 获取cookie
     * @param request
     * @param key
     * @return
     */
    public static String getCookie(HttpServletRequest request, String key){
        Cookie[] cookies = request.getCookies();
        if(Utils.isEmpty(cookies)){
            return null;
        }
        for (Cookie cookie : cookies) {
            if(key.equals(cookie.getName())){
                return cookie.getValue();
            }
        }
        return null;
    }

    public static void deleteCookie(HttpServletResponse response, String key){
        setCookie(response,key,null, 0);
    }
}
